package com.igeek.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.car.entity.Checi;
import com.igeek.car.mapper.CheCiMapper;
import com.igeek.car.service.CheCiService;
import com.igeek.car.utils.POIUtils;
import com.igeek.car.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author bbjs
 * @since 2024/12/9
 */
@Service
public class CheCiServiceImpl extends ServiceImpl<CheCiMapper, Checi> implements CheCiService {
    @Autowired
    private CheCiMapper cheCiMapper;
    @Override
    public Page<Checi> findPage(PageQueryVO vo) {
        //1.封装分页数据
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        Page<Checi> page = Page.of(currentPage, pageSize);
        //2.封装查询条件
        String queryString = vo.getQueryString();
        LambdaQueryWrapper<Checi> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasLength(queryString) , Checi::getDispatchId , queryString)
                .or()
                .like(StringUtils.hasLength(queryString) , Checi::getDriverName , queryString);

        //3.执行分页条件查询
        Page<Checi> CheCiPage = this.page(page, lambdaQueryWrapper);
        return CheCiPage;
    }

    //删除调度
    @Override
    public boolean del(String dispatchId) {
        // 1.检查调度是否存在
        if (ObjectUtils.isEmpty(dispatchId) || this.baseMapper.selectById(dispatchId) == null) {
            throw new RuntimeException("调度不存在！");
        }

        // 2. 获取调度记录
        Checi checi = this.baseMapper.selectById(dispatchId);

        // 3. 检查调度状态是否为“已调度”或“调度中”
        if ("已调度".equals(checi.getDispatchStatus()) || "调度中".equals(checi.getDispatchStatus())) {
            throw new RuntimeException("该调度任务处于进行中或已调度状态，无法删除！");
        }

        // 4. 执行删除操作
        int result = this.baseMapper.deleteById(dispatchId);
        return result > 0;
    }


    @Override
    public List<String> listAllDispatchIds() {
        // 1.查询所有车次信息
        List<Checi> checiList = this.list();

        // 2.检查车次列表是否为空
        if (CollectionUtils.isEmpty(checiList)) {
            throw new RuntimeException("车次信息为空！");
        }

        // 3.提取车次号并返回
        return checiList.stream()
                .map(Checi::getDispatchId)
                .collect(Collectors.toList());
    }
    @Transactional
    @Override
    public boolean upload(MultipartFile excelFile) throws IOException {
        if (excelFile != null) {
            // 通过POI读取Excel文件上的内容
            List<String[]> strings = POIUtils.readExcel(excelFile);
            System.out.println("读取到的 Excel 数据：");
            for (String[] row : strings) {
                System.out.println(Arrays.toString(row));
            }
            if (strings == null || strings.isEmpty()) {
                System.out.println("Excel 文件内容为空！");
                return false;
            }
            // 将 List<String[]> 转换为 List<Checi>
            List<Checi> checiList = strings.stream().map(string -> {
                Checi checi = new Checi();
                checi.setDispatchId(string[0]);
                checi.setRouteId(string[1]);
                checi.setTripId(string[2]);
                checi.setDispatchTime(LocalDateTime.parse(string[3], DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
                checi.setExpectedDepartureTime(LocalDateTime.parse(string[4], DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
                checi.setActualDepartureTime(LocalDateTime.parse(string[5], DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
                checi.setAdjustedExpectedArrivalTime(LocalDateTime.parse(string[6], DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
                checi.setVehicleId(string[7]);
                checi.setDriverId(string[8]);
                checi.setDriverName(string[9]);
                checi.setDispatchStatus(string[10]);
                checi.setDispatchReason(string[11]);
                return checi;
            }).collect(Collectors.toList());
            // 逐条检查并更新或插入数据
            for (Checi checi : checiList) {
                String operationResult = updateCheci(checi);
                System.out.println(operationResult); // 打印提示信息
            }
            return true;
        }
        return false;
    }

    // 根据调度编号更新车次信息
    private String updateCheci(Checi checi) {
        LambdaQueryWrapper<Checi> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Checi::getDispatchId, checi.getDispatchId());

        // 判断当前上传的调度编号是否存在数据
        Long count = this.baseMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            // 若存在，则更新数据
            Checi existingCheci = this.baseMapper.selectOne(lambdaQueryWrapper);
            if (!existingCheci.equals(checi)) {
                this.baseMapper.update(checi, lambdaQueryWrapper);
                return "调度编号 " + checi.getDispatchId() + " 数据已更新成功！";
            }
            return "调度编号 " + checi.getDispatchId() + " 数据没有变化，跳过更新。";
        } else {
            // 若不存在，则插入数据
            this.baseMapper.insert(checi);
            return "调度编号 " + checi.getDispatchId() + " 数据已插入成功！";
        }
    }

}
